package com.dudu.timer;

import java.util.Date;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.dudu.dao.SmsInfoDao;
import com.dudu.utils.DateUtils;
import com.dudu.utils.DictionaryUtils;

import core.CoreDao;
import core.CoreDaoInvoke;
import core.util.EmailSend;


public class SmsWatchingJob implements Job {
	//log日志
	public static final Logger log = core.util.Logger.getLogger(SmsWatchingJob.class.getName());
	//数据库连接
	private CoreDao coreDao = CoreDaoInvoke.getInstance();
	//
	private SmsInfoDao smsInfoDao = new SmsInfoDao();

	/**
	 * 每10分钟监测一次
	 * 有调用通道发送短信验证码失败或验证码下发延时20秒
	 * 邮件的发送时间段为早8点至晚10点
	 */
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		log.info("执行短信验证码监控job");
		try{		
			String emailAdressStr = DictionaryUtils.getValueByTypeAndKey("report_email", "sms");	//获得接收邮箱
			if(StringUtils.isNotBlank(emailAdressStr)){			
				StringBuffer content = new StringBuffer();	//邮件内容
				int timeOfHour = Integer.valueOf(DateUtils.getCurrentTime().substring(11, 13)); //时间：小时
				if(timeOfHour >= 8 && timeOfHour <= 22){ //早八点至晚十点
					Date now = new Date();
					Date now_10 = new Date(now.getTime() - 600000); //10分钟前的时间
					String beginTime = DateUtils.getFormatTime(now_10, "yyyy-MM-dd HH:mm:ss");  
					String endTime = DateUtils.getFormatTime(now, "yyyy-MM-dd HH:mm:ss");	
					String[] emailAdressArray = emailAdressStr.split(",");
					JSONObject dataJson = smsInfoDao.queryWatchingAmounts(coreDao, beginTime, endTime);
					if(dataJson != null){
						int totalAmount = dataJson.optInt("totalAmount"); 
						int errorAmount = dataJson.optInt("errorAmount");
						int delayAmount = dataJson.optInt("delayAmount");
						int noStatusAmount = dataJson.optInt("noStatusAmount");
						if(errorAmount > 0 || delayAmount >0 || noStatusAmount >0){ //有调用通道失败和下发延时超过20秒的发邮件
							content.append(beginTime + " - " + endTime + "时间段内,共提交"+totalAmount+"条短信验证码，调用通道失败"+errorAmount+"条，"
									+ "下发延时（超过20秒）" + (delayAmount+noStatusAmount) + "条。");
							for(String emailAdress:emailAdressArray){
								Thread.sleep(1000*10); //邮件服务器不支持连续发送
								EmailSend.sendMail(emailAdress, "短信验证码监控", content.toString(), null, null); //发送邮件
							}
						}
					}	
				}
			}else{
				log.info("未配置短信验证码监控接收邮件地址");
			}
		}catch(Exception ex){
			ex.getMessage();
			log.info("短信验证码监控job error");
		}
	}

}
